<script setup>
import { ref, onMounted } from "vue";
import api from '../api/order.js';
import lodash from 'lodash';
import dayjs from 'dayjs';

// 页面数据
const pageData = ref({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 1
});

// 搜索文本
const searchText = ref('');

// 对话框控制
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const deleteDialogVisible = ref(false);

// 表单对象
const addObj = ref({
  status: '',
  uname: '',
  dname: '',
  oquantity: '',
  oprice: '',
  otime: dayjs().format('YYYY-MM-DD')
});

const editObj = ref({
  status: '',
  oid: '',
  uname: '',
  dname: '',
  oquantity: '',
  oprice: '',
  otime: ''
});

const deleteObj = ref({
  oid: ''
});

// 状态选项
const statusOptions = ref([
  { label: '已完成', value: 'completed' },
  { label: '处理中', value: 'processing' },
  { label: '已取消', value: 'cancelled' }
]);

// 生命周期钩子
onMounted(() => {
  getTableList();
});

// 获取表格数据
const getTableList = async () => {
  const params = {
    current: pageData.value.current,
    size: pageData.value.size,
    searchtext: searchText.value || ''
  };

  try {
    const result = await api.getOrderPage(params);
    pageData.value = result;
  } catch (error) {
    console.error("获取订单数据失败:", error);
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pageData.value.size = size;
  pageData.value.current = 1;
  getTableList();
};

const handleCurrentChange = (current) => {
  pageData.value.current = current;
  getTableList();
};

// 搜索处理
const handleSearch = () => {
  pageData.value.current = 1;
  getTableList();
};

// 删除订单
const handleDelete = (row) => {
  deleteObj.value = {
    oid: row.oid,
    dname: row.dname
  };
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  try {
    await api.deleteOrder(deleteObj.value.oid);
    getTableList();
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error("删除订单失败:", error);
  }
};

// 编辑订单
const handleEdit = (row) => {
  editDialogVisible.value = true;
  editObj.value = { ...row };
};

const handlerEditConfirm = async () => {
  try {
    const submitData = {
      ...editObj.value,
    };

    await api.editOrder(submitData);
    getTableList();
    editDialogVisible.value = false;
  } catch (error) {
    console.error("更新订单失败:", error);
  }
};

// 新增订单
const handlerAddConfirm = async () => {
  try {
    const submitData = {
      ...addObj.value,
    };

    await api.addOrder(submitData);
    getTableList();
    addDialogVisible.value = false;
    // 重置表单
    addObj.value = {
      status: '',
      uname: '',
      dname: '',
      oquantity: '',
      oprice: '',
      otime: dayjs().format('YYYY-MM-DD')
    };
  } catch (error) {
    console.error("添加订单失败:", error);
  }
};

// 取消操作
const handlerAddCancel = () => {
  addDialogVisible.value = false;
  addObj.value = {
    status: '',
    uname: '',
    dname: '',
    oquantity: '',
    oprice: '',
    otime: dayjs().format('YYYY-MM-DD')
  };
};

const handlerEditCancel = () => {
  editDialogVisible.value = false;
};
</script>

<template>
  <div class="order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <p class="page-subtitle">管理系统药品订单信息</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="global-card operation-card">
      <el-row :gutter="20" align="middle">
        <el-col :span="8">
          <el-input
              v-model="searchText"
              placeholder="搜索订单ID/药品名称/用户名"
              clearable
              @clear="handleSearch"
          >
            <template #prefix>
              <el-icon class="search-icon">
                <Search/>
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch" class="action-button">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
        </el-col>
        <el-col :span="4" :offset="8">
          <el-button type="success" @click="addDialogVisible = true" class="action-button new-order-button">
            <el-icon>
              <Plus/>
            </el-icon>
            新增订单
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 订单表格 -->
    <div class="global-card data-card">
      <el-table :data="pageData.records" style="width: 100%" stripe>
        <el-table-column prop="oid" label="订单ID" width="100" align="center"/>
        <el-table-column prop="dname" label="药品名称" width="150" align="center">
          <template #default="{ row }">
            <el-tag type="info" class="drug-tag">{{ row.dname }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="uname" label="用户名称" width="120" align="center"/>
        <el-table-column prop="oquantity" label="数量" width="100" align="center"/>
        <el-table-column prop="oprice" label="价格(元)" width="120" align="center">
          <template #default="{ row }">
            {{ row.oprice }}
          </template>
        </el-table-column>
        <el-table-column prop="otime" label="订单时间" width="150" align="center"/>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'completed' ? 'success' :
                           row.status === 'processing' ? 'warning' : 'danger'">
              {{
                row.status === 'completed' ? '已完成' :
                    row.status === 'processing' ? '处理中' : '已取消'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
                size="small"
                @click="handleEdit(row)"
                icon="Edit"
                class="edit-button"
            >编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
                icon="Delete"
                class="delete-button"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pageData.current"
            v-model:page-size="pageData.size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="custom-pagination"
        />
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除订单"
        width="400px"
        class="delete-dialog"
    >
      <div class="dialog-content">
        <el-icon class="dialog-icon" color="#F56C6C">
          <WarningFilled/>
        </el-icon>
        <p>确定要删除订单 <strong>#{{ deleteObj.oid }}</strong> ({{ deleteObj.dname }}) 吗？</p>
        <p class="warning-text">此操作不可恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false" class="cancel-button">取消</el-button>
        <el-button type="danger" @click="confirmDelete" class="confirm-delete-button">确认删除</el-button>
      </template>
    </el-dialog>

    <!-- 新增订单对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增订单" class="form-dialog">
      <div class="dialog-header">
        <el-icon>
          <DocumentAdd/>
        </el-icon>
        <span>添加新订单信息</span>
      </div>
      <el-form :model="addObj" label-width="100px" class="order-form">
        <el-form-item label="药品名称">
          <el-input v-model="addObj.dname" autocomplete="off" placeholder="请输入药品名称"/>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="addObj.uname" autocomplete="off" placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="addObj.oquantity" :min="1" :max="999"/>
        </el-form-item>
        <el-form-item label="价格(元)">
          <el-input-number v-model="addObj.oprice" :min="0" :max="99999" :precision="2"/>
        </el-form-item>
        <el-form-item label="订单时间">
          <el-date-picker
              v-model="addObj.otime"
              type="date"
              placeholder="选择订单日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="addObj.status" placeholder="请选择状态">
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlerAddCancel" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="handlerAddConfirm" class="confirm-button">确认新增</el-button>
      </template>
    </el-dialog>

    <!-- 编辑订单对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑订单" class="form-dialog">
      <div class="dialog-header">
        <el-icon>
          <Edit/>
        </el-icon>
        <span>编辑订单信息</span>
      </div>
      <el-form :model="editObj" label-width="100px" class="order-form">
        <el-form-item label="订单ID">
          <el-input v-model="editObj.oid" disabled/>
        </el-form-item>
        <el-form-item label="药品名称">
          <el-input v-model="editObj.dname" autocomplete="off" placeholder="请输入药品名称"/>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="editObj.uname" autocomplete="off" placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="editObj.oquantity" :min="1" :max="999"/>
        </el-form-item>
        <el-form-item label="价格(元)">
          <el-input-number v-model="editObj.oprice" :min="0" :max="99999" :precision="2"/>
        </el-form-item>
        <el-form-item label="订单时间">
          <el-date-picker
              v-model="editObj.otime"
              type="date"
              placeholder="选择订单日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="editObj.status" placeholder="请选择状态">
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlerEditCancel" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="handlerEditConfirm" class="confirm-button">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.page-title {
  color: #1a3b6d;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.page-subtitle {
  color: #606266;
  font-size: 15px;
}

/* 卡片样式 */
.operation-card {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.data-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

/* 按钮样式 */
.action-button {
  padding: 8px 15px;
  font-weight: 500;
  transition: all 0.3s;
  border-radius: 4px;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.new-order-button {
  background: linear-gradient(135deg, #409eff, #79bbff);
  border: none;
  color: white;
}

.new-order-button:hover {
  background: linear-gradient(135deg, #79bbff, #409eff);
}

.edit-button {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.delete-button {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #1565c0;
}

/* 标签样式 */
.drug-tag {
  background-color: #f0f9ff;
  border-color: #cce6ff;
  color: #409eff;
}

/* 分页样式 */
.pagination-wrapper {
  padding: 20px 0;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.custom-pagination {
  background: white;
  padding: 10px 15px;
  border-radius: 8px;
}

/* 对话框样式 */
.delete-dialog {
  border-radius: 8px;
}

.dialog-content {
  text-align: center;
  padding: 20px;
}

.dialog-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.warning-text {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 10px;
}

.form-dialog {
  border-radius: 8px;
}

.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.dialog-header .el-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #409eff;
}

.dialog-header span {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.order-form {
  padding: 0 20px;
}

/* 按钮样式 */
.cancel-button {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.confirm-button {
  background: linear-gradient(135deg, #409eff, #79bbff);
  border: none;
  color: white;
}

.confirm-button:hover {
  background: linear-gradient(135deg, #79bbff, #409eff);
}

.confirm-delete-button {
  background: linear-gradient(135deg, #f56c6c, #f89898);
  border: none;
  color: white;
}

.confirm-delete-button:hover {
  background: linear-gradient(135deg, #f89898, #f56c6c);
}

/* 输入框样式 */
.search-icon {
  color: #409eff;
  font-size: 18px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-card .el-row .el-col {
    margin-bottom: 10px;
  }

  .operation-card .el-col:last-child {
    margin-bottom: 0;
  }

  .new-order-button {
    width: 100%;
  }
}
</style>